package com.cz.validate.controller;

import com.cz.validate.model.ProductInfo;
import com.cz.validate.service.ProductInfoService;
import com.cz.validate.vo.ProductInfoQueryVo;
import com.cz.validate.vo.ProductInfoVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @Description todo
 * @Author cz
 * @Date 2022/6/23
 */
@RestController
@RequestMapping("/product/v1")
public class ProductInfoController {

    @Resource
    private ProductInfoService productInfoService;

    /**
     * 测试使用 BindingResult 捕获异常
     * JSON格式传递参数
     *
     * @param vo     产品
     * @param result 异常捕获类
     */
    @PostMapping("/findByVo/1")
    public void findByVo(@RequestBody @Valid ProductInfoQueryVo vo, BindingResult result) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(result.toString());
        System.out.println(vo.toString());
        if (result.hasErrors()) {
            for (ObjectError error : result.getAllErrors()) {
                System.out.println(mapper.writeValueAsString("捕获到的单个error对象:" + error));
                System.out.println(error.getDefaultMessage());
            }
        }
    }

    /**
     * 测试不捕获异常，使用全局异常拦截器拦截
     * urlencoded方式传参
     *
     * @param vo 视图对象
     * @return ResultVo
     */
    @PostMapping("/findByVo/2")
    public ProductInfoVo findByVo(@Valid ProductInfoQueryVo vo) {
        ProductInfo filter = new ProductInfo();
        BeanUtils.copyProperties(vo, filter);
        //查数据库，此处简写
        return productInfoService.getAllByFilter(filter);
    }
}
